package fragment;

import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.zin.viewpagerfragment.Constans;
import com.zin.viewpagerfragment.MainActivity;
import com.zin.viewpagerfragment.R;

import org.com.cctest.view.XListView;

import java.util.ArrayList;
import java.util.List;

import adapter.NewsAdapter;
import entity.ListBean;
import entity.NewsData;
import util.Utils;


public class NewsFragment extends Fragment implements XListView.IXListViewListener {
    XListView lv_news;
    NewsAdapter adapter;
    private Handler mhandler = new Handler();
    private int page = 1;
    private List<ListBean> list = new ArrayList<ListBean>();
    private String baseurl;
    private String type;
    private String url;
    private String newstype; // 根据新闻的类型分辨
    String cache_filename; //缓存文件名

    public NewsFragment(String type) {
        this.type = type;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_selection_common,
                container, false);

        //TextView tv_tabName = (TextView) rootView.findViewById(R.id.tv_tabName);
        Bundle bundle = getArguments();
        lv_news = (XListView) rootView.findViewById(R.id.xListView);
        lv_news.setPullLoadEnable(true); //开关加载更多
        lv_news.setPullRefreshEnable(true);// 开关刷新功能
        //  tv_tabName.setText(bundle.getString(MainActivity.ARGUMENTS_NAME, ""));
        lv_news.setXListViewListener(this);


        adapter = new NewsAdapter(getActivity());
        lv_news.setAdapter(adapter);
        newstype = bundle.getString(Constans.KEY_id, "");
        cache_filename = Constans.SD_NEWS_DIR + "/cache_" + newstype + ".txt";


        if (Utils.hasConnected()) {
            getJsonData(type,page);
        } else {
            String strjson = Utils.readFileSdcardFile(cache_filename);
            parseData(strjson);

        }


        return rootView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    //  http://wangyi.butterfly.mopaasapp.com/news/api?type=tech&page=1&limit=12

    @Override
    public void onRefresh() {
        //更新
        mhandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                list.clear();
                //   url=baseurl+"_"+pageno+".json";

                getJsonData(type,page);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        //加载更多

        mhandler.postDelayed(new Runnable() {//延迟调用
            @Override
            public void run() {
                if (Utils.hasConnected()) {
                    page++;// 往下翻页
                }
                //    url = base_url + "_" + pageno + ".json";
                //      Log.i("spl", "上拉翻页," + url);
                getJsonData(type,page);
            }
        }, 2000);
    }


    public void getJsonData(String type,int page) {


        new HttpUtils().send(HttpRequest.HttpMethod.GET,
                "http://wangyi.butterfly.mopaasapp.com/news/api?type=" + type + "&page=" + page + "&limit=12",
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String json = responseInfo.result;
                        //    System.out.println("}}}}}" + json);
                        //保存json文件
                        //   NewsData newdata = JSON.parseObject(json, NewsData.class);
                        // list=newdata.getList();
                        Utils.writeFileSdcardFile(cache_filename,json);
                        parseData(json);
                        //   timer.schedule(timetask, 2000); //定时器

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                        Utils.show("当前网络不可访问");
                        String strjson = Utils.readFileSdcardFile(cache_filename);
                        parseData(strjson);
                    }
                });

    }

    boolean online = false;
    private void parseData(String strJson) {
        // 解析JSON

        if (strJson.equals("")){
         list.clear();
        }else
        {
            NewsData newdata = JSON.parseObject(strJson, NewsData.class);
            //newsList = JSON.parseObject(strJson, NewsList.class);

            // toplist = newsList.getData().getTopnews();

            if (Utils.hasConnected()) {
                List<ListBean> temp = newdata.getList();
                list.addAll(temp);
                System.out.println("NewsFragment========" + list.size());
            } else {
                list = newdata.getList();
            }
        }
        // 更新数据
        System.out.println("NewsFragmenttwo========" + list.size());
        adapter.setList(list);
      /*  if (first) {
            lv_news.setAdapter(adapter);
        }*/
        adapter.notifyDataSetChanged();

        //     initData(toplist);
        onLoad();


    }

    long loadTime = System.currentTimeMillis();

    //加载完毕
    private void onLoad() {
        lv_news.stopRefresh();// 停止更新
        lv_news.stopLoadMore();// 停止加载更多
        lv_news.setRefreshTime(Utils.getTime(loadTime));// 显示更新时间
        loadTime = System.currentTimeMillis();// 上次更新时间
    }


}














